require 'net/http'
require 'json'

load 'wechat_api.rb'
load 'rds_api.rb'
@rds = @rds_tt

def create_mp_tag(tag_group_name)
    access_token = get_wechat_access_token  #'YOUR_ACCESS_TOKEN'
    url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=#{access_token}"

    payload = {
        tag: {
            name: tag_group_name
        }
    }

    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(uri.request_uri, { 'Content-Type' => 'application/json' })
    request.body = payload.to_json

    response = http.request(request)
    result = JSON.parse(response.body)

    if result['errcode'].to_i == 0
        puts "Tag group created successfully!"
        return result['tag']['id'] # 返回标签组ID
    else
        puts "Failed to create tag group: #{result['errmsg']}"
        return nil
    end
end

def add_user_to_mp_tag(openid, tag_id)
    openid_list = [openid]
    add_users_to_mp_tag([openid_list], tag_id)
end

def add_users_to_mp_tag(openid_list, tag_id)
    access_token = get_wechat_access_token  #'YOUR_ACCESS_TOKEN'
    url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=#{access_token}"

    payload = {
        openid_list: openid_list, 
        tagid: tag_id
    }

    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(uri.request_uri, { 'Content-Type' => 'application/json' })
    request.body = payload.to_json

    response = http.request(request)
    result = JSON.parse(response.body)

    if result['errcode'].to_i == 0
        puts "User added to tag successfully!"
    else
        puts "Failed to add user to tag: #{result['errmsg']}"
    end
end

def get_mp_tag_id_by_name(tag_name)
    access_token = get_wechat_access_token  #'YOUR_ACCESS_TOKEN'
    url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=#{access_token}"

    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Get.new(uri.request_uri)

    response = http.request(request)
    result = JSON.parse(response.body)

    if result['errcode'].to_i == 0
        tags = result['tags']
        tag = tags.find { |t| t['name'] == tag_name }
        if tag
            puts "Tag ID for '#{tag_name}': #{tag['id']}"
            return tag['id']
        else
            puts "Tag '#{tag_name}' not found"
            return nil
        end
    else
        puts "Failed to get tags: #{result['errmsg']}"
        return nil
    end
end

def get_openid_list_for_tupal
    sql = "select uid, openid from tutem_mall.eb_wechat_user where uid in (select uid from tutem_mall.eb_tupal) and openid is not null"
    openid_list = []
    (queryRds(sql)).each do |q|
        openid_list += [q['openid']]
    end
    return openid_list
end

def tag_openid_list_as tag_name, openid_list
    tag_id = get_mp_tag_id_by_name(tag_name)
    tag_id = create_mp_tag(tag_name) if tag_id.nil?
    add_users_to_mp_tag(openid_list, tag_id)
end

# 使用示例：将现有的图腾之友用户建立到组图腾之友去
def tag_20230616
    #get_wechat_access_token true
    tag_name = '图腾之友'
    openid_list = get_openid_list_for_tupal
    openid_list.each_slice(10).to_a.each do |small_list|
        tag_openid_list_as tag_name, small_list
    end
end
